package com.ruoyi.web.controller.content;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.shop.common.constant.Constants;
import com.ruoyi.shop.common.constant.MinioBuckets;
import com.ruoyi.shop.common.utils.SnowflakeIdWorker;
import com.ruoyi.shop.modules.domain.Attachment;
import com.ruoyi.shop.modules.service.IAttachmentService;
import com.ruoyi.shop.modules.service.IMinioService;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @Project: Shop
 * @Package: com.ruoyi.web.controller.content
 * @Author: JinChen Zhu
 * @CreateTime: 2024-05-22  13:23
 * @Version: 1.0
 */

@RestController
@RequestMapping("/content/minio")
@ApiResponses(@ApiResponse(code = 200, message = "处理成功"))
@Slf4j
public class MinioController {
    @Autowired
    private IMinioService minioService;
    @Autowired
    private IAttachmentService attachmentService;
    private SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);


    @PostMapping("/uploadPic")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws Exception {
        // 判断文件是否为空
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }

        //获取当前用户信息
        String username = SecurityUtils.getUsername();
        // 获取文件字节数组
        byte[] bytes = file.getBytes();
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        // 判断文件类型是否支持
        if (!fileSuffix.equalsIgnoreCase(".jpg") &&
                !fileSuffix.equalsIgnoreCase(".png") &&
                !fileSuffix.equalsIgnoreCase(".gif")) {
            return AjaxResult.error("文件类型不支持");
        }
        // 获取文件大小
        long fileSize = file.getSize();
        // 获取文件的MD5值
        String md5Hex = DigestUtils.md5Hex(bytes);
        // 创建临时文件
        File tempFile = File.createTempFile(fileName, fileSuffix);
        // 将MultipartFile转换为File
        file.transferTo(tempFile);
        // 获取临时文件路径
        String filePath = tempFile.getAbsolutePath();
        // 获取媒体类型
        String contentType = file.getContentType();
        // 雪花算法生成minio中的对象名
        String snowflakeId = String.valueOf(idWorker.nextId());
        String objectName = snowflakeId + fileSuffix;

        // 上传到 Minio 并检查上传是否成功
        boolean uploadSuccess = minioService.putObject(MinioBuckets.IMAGE_BUCKET, objectName, filePath, contentType, Constants.TEMP_FILE_EXPIRATION);
        String url = minioService.getObjectUrl(MinioBuckets.IMAGE_BUCKET, objectName);
        // 删除临时文件
        tempFile.delete();

        // 如果上传失败，返回错误信息
        if (!uploadSuccess) {
            log.error("上传文件到Minio失败");
            return AjaxResult.error("上传失败");
        }

        // 构建附件对象
        Attachment attachment = new Attachment();
        // 查询文件是否存在
        Attachment attachmentExist = attachmentService.selectAttachmentByMD5(md5Hex);
        if (attachmentExist != null) {
            return AjaxResult.error("文件已存在", attachmentExist.getName());
        }

        // 设置附件属性
        attachment.setId(snowflakeId);
        attachment.setName(fileName);
        attachment.setExt(fileSuffix);
        attachment.setLenght(fileSize);
        attachment.setUrl(url);
        attachment.setMd5(md5Hex);
        attachment.setStatus(Constants.STATUS_NORMAL);
        attachment.setUpdateBy(username);
        attachment.setCreateBy(username);


        // 如果一切顺利，返回成功信息
        log.info("上传文件到Minio成功,访问地址：{}", url);
        return AjaxResult.success("上传成功", attachment);
    }


    //删除图片接口
    @PostMapping("/deletePic")
    public AjaxResult delete(@RequestParam("fileName") String fileName) {
        boolean deleteSuccess = minioService.removeObject(MinioBuckets.IMAGE_BUCKET, fileName);
        if (deleteSuccess) {
            return AjaxResult.success("删除成功", fileName);
        } else {
            return AjaxResult.error("删除失败");
        }
    }
}